package com.example.interviewassistant;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;
import android.util.Log;
import android.content.Context;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;

// 引入PdfBox相关类
import com.tom_roush.pdfbox.pdmodel.PDDocument;
import com.tom_roush.pdfbox.text.PDFTextStripper;
import com.tom_roush.pdfbox.android.PDFBoxResourceLoader;

public class ResumeUploader {
    private static final String TAG = "ResumeUploader";
    private static final int MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB

    public static void selectResume(android.app.Activity activity, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        String[] mimeTypes = {"application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "text/plain"};
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        activity.startActivityForResult(intent, requestCode);
    }

    public static String parseResumeContent(android.content.Context context, Uri uri) throws Exception {
        // 先获取文件信息
        String fileName = getFileName(context, uri);
        long fileSize = getFileSize(context, uri);
        
        // 检查文件大小
        if (fileSize > MAX_FILE_SIZE) {
            throw new Exception("文件过大，不能超过5MB");
        }
        
        // 根据文件类型选择解析方式
        String mimeType = context.getContentResolver().getType(uri);
        Log.d(TAG, "Parsing file: " + fileName + ", type: " + mimeType + ", size: " + fileSize);
        
        String content = "";
        if (mimeType != null) {
            if (mimeType.equals("text/plain")) {
                content = parseTextFile(context, uri);
            } else if (mimeType.contains("pdf")) {
                content = parsePdfFile(context, uri);
            } else if (mimeType.contains("wordprocessingml.document") || mimeType.contains("msword")) {
                // 简单处理，实际应用中应使用POI等库
                content = "Word文件解析暂不完善，请使用TXT或PDF格式\n文件名: " + fileName;
            }
        } else {
            // 兜底方案：尝试作为文本文件解析
            try {
                content = parseTextFile(context, uri);
            } catch (Exception e) {
                Log.e(TAG, "Failed to parse as text: " + e.getMessage());
                throw new Exception("不支持的文件格式，请使用PDF、DOCX或TXT文件");
            }
        }
        
        // 对简历内容进行脱敏处理
        String maskedContent = SensitiveDataMask.maskSensitiveInfo(content);
        Log.d(TAG, "Resume content masked for privacy");
        
        return maskedContent;
    }
    
    private static String parsePdfFile(Context context, Uri uri) throws Exception {
        // 初始化PdfBox
        PDFBoxResourceLoader.init(context);
        
        try (InputStream is = context.getContentResolver().openInputStream(uri)) {
            if (is == null) {
                throw new Exception("无法打开PDF文件");
            }
            
            try (PDDocument document = PDDocument.load(is)) {
                PDFTextStripper stripper = new PDFTextStripper();
                String text = stripper.getText(document);
                
                if (text.trim().isEmpty()) {
                    // 如果提取的文本为空，可能是扫描件或图片PDF
                    return "PDF文件内容为空或是扫描件，无法提取文本\n文件名: " + getFileName(context, uri);
                }
                
                return text;
            } catch (IOException e) {
                Log.e(TAG, "Error parsing PDF", e);
                throw new Exception("解析PDF文件失败: " + e.getMessage());
            }
        }
    }
    
    private static String parseTextFile(android.content.Context context, Uri uri) throws Exception {
        StringBuilder content = new StringBuilder();
        try (InputStream is = context.getContentResolver().openInputStream(uri);
             BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
            
            if (is == null) {
                throw new Exception("无法打开文件流");
            }
            
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
            
            if (content.length() == 0) {
                throw new Exception("文件内容为空");
            }
            
            return content.toString();
        } catch (Exception e) {
            Log.e(TAG, "Error parsing resume content", e);
            throw e;
        }
    }
    
    private static String getFileName(android.content.Context context, Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    if (nameIndex >= 0) {
                        result = cursor.getString(nameIndex);
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "Error getting file name", e);
            }
        }
        if (result == null) {
            result = uri.getLastPathSegment();
        }
        return result != null ? result : "unknown";
    }
    
    private static long getFileSize(android.content.Context context, Uri uri) {
        long size = -1;
        if (uri.getScheme().equals("content")) {
            try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
                    if (sizeIndex >= 0 && !cursor.isNull(sizeIndex)) {
                        size = cursor.getLong(sizeIndex);
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "Error getting file size", e);
            }
        }
        if (size < 0) {
            // 如果无法通过查询获取文件大小，尝试打开文件并读取
            try (InputStream is = context.getContentResolver().openInputStream(uri)) {
                if (is != null) {
                    size = is.available();
                }
            } catch (Exception e) {
                Log.e(TAG, "Error calculating file size", e);
            }
        }
        return size;
    }
} 